import React, {useEffect, useState} from 'react'
import {Button, Modal, Popover, Switch, Table, Tag} from "antd";
import axios from "axios";
import {DeleteOutlined, FormOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
const {confirm}=Modal
export default function RightList() {
    const [loading, setLoading] = useState(false);

    const [dataSource, setdatasource] = useState([])
    useEffect(()=>{
        axios.get(`http://localhost:5000/rights?_embed=children`).then(res => {
            setdatasource(res.data)})
    }, [])

    //删除
    const deleteMethod = (item)=>{
        console.log(item)
        if (item.grade === 1 ) {
            setdatasource(dataSource.filter(data => data.id !== item.id))
            axios.delete(`http://localhost:5000/rights/${item.id}`)
            // setLoading(false)
        }else{
            console.log(item.rightId)
            //找出上级ID
            let list = dataSource.filter(data=>data.id === item.rightId)
            console.log(list)
            list[0].children = list[0].children.filter(data=>data.id!==item.id)
            console.log(list, dataSource)
            setdatasource([...dataSource])
            axios.delete(`http://localhost:5000/children/${item.id}`)
        }
    }
    const confirmMethod = (item) =>{
        confirm({
            title: '你确定要删除吗?',
            icon: <ExclamationCircleOutlined />,
            content: 'Some descriptions',
            onOk() {
                // console.log('确定');
                deleteMethod(item)
            },
            onCancel() {
                console.log('删除');
            },
        });
    }

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            render:(id)=>{
                return <b>{id}</b>
            }

        },
        {
            title: '权限名称',
            dataIndex: 'title',

        },
        {
            title: '路径',
            dataIndex: 'key',
            render:(key)=>{
                return <Tag color="orange">{key}</Tag>
            }

        },
        {
            title: '操作',
            render:(item)=>{
                // console.log(item)
                return <div>
                    <Button type="danger" shape="circle" icon={<DeleteOutlined />} onClick={()=>confirmMethod(item)}></Button>

                        <Button type="primary" shape="circle" icon={<FormOutlined />}></Button>

                </div>
            }
        },
        {
            title: '是否开启',
            render:(item)=>{
                return <div>
                    <Switch checked={item.permission}></Switch>
                </div>
            }
        }
    ];

    return (
        <div>
            <Table dataSource={dataSource} columns={columns}
                   loading={loading}
            pagination={{
                pageSize: 5
            }}
            />;
        </div>
    )
}
